using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QxFramework.Core;
using UnityEngine.UI;

public class HPBarOfTrain : UIBase
{
    public override int UILayer => 4;

    private Canvas _canvas;
    private TrainBody _trainBody;
    private RectTransform _rectTransform;
    private Vector2 position;
    private RectTransform hpBar;
    private RectTransform maxHPBar;
    public override void OnDisplay(object args)
    {
        base.OnDisplay(args);
        _canvas = GameObject.Find("Canvas").GetComponent<Canvas>();
        _trainBody = (TrainBody)args;
        _rectTransform = GetComponent<RectTransform>();
        maxHPBar = transform.Find("MaxHPBar").GetComponent<RectTransform>(); 
        hpBar = transform.Find("CurrentHPBar").GetComponent<RectTransform>();

        maxHPBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 205);
        if (!_trainBody.isFlip)
        {
            hpBar.GetComponent<Image>().color = new Color(255f/255, 0, 0);
            maxHPBar.GetComponent<Image>().color = new Color(118f/255, 0, 0);
        }
        else
        {
            hpBar.GetComponent<Image>().color = new Color(71f/255, 230/255f, 253f/255);
            maxHPBar.GetComponent<Image>().color = new Color(0, 76f/255, 104f/255);
        }

    }
    public Vector3 WorldToUIPosition(Vector3 worldPosition,Canvas canvas)
    {
        Vector2 UIPosition;
        var screenPosition = Camera.main.WorldToScreenPoint(worldPosition);
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.GetComponent<RectTransform>(), screenPosition, canvas.worldCamera, out UIPosition);
        return UIPosition;
    }
    void Start()
    {
        
    }

    private bool isBule=false;
    void Update()
    {
        position = WorldToUIPosition(_trainBody.transform.position, _canvas);
        _rectTransform.localPosition = position;
        if (!_trainBody.isFlip)
            hpBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, _trainBody.health / _trainBody.maxHealth * 200);
        else
            hpBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, _trainBody.counter / _trainBody.timeToFix * 200);

        if (_trainBody.isFlip && !isBule)
        {
            isBule = true;
            hpBar.GetComponent<Image>().color = new Color(71f/255, 230f/255, 253f/255);
            maxHPBar.GetComponent<Image>().color = new Color(0, 76f/255, 104f/255);
        }
        else if (!_trainBody.isFlip && isBule)
        {
            isBule = false;
            hpBar.GetComponent<Image>().color = new Color(255f/255, 0, 0);
            maxHPBar.GetComponent<Image>().color = new Color(118f/255, 0, 0);
        }
    }
}
